##

rm(list = ls())

## 

library(tidyverse)

## Load saved results

res_df_rdd_muni <- read_rds('data/rdd_municipal_results.rds') %>% 
  mutate(unit = 'Municipal election') %>% 
  filter(str_detect(outcome, "agg|turnout"))

res_df_rdd_bundestag <- read_rds('data/rdd_federal_results.rds') %>% 
  mutate(unit = 'Federal election') %>% 
  mutate(outcome = str_remove(outcome, "_party")) %>% 
  filter(str_detect(outcome, "agg|turnout"))

res_df_rdd_landtag <- read_rds('data/rdd_state_results.rds') %>% 
  mutate(unit = 'State election') %>% 
  filter(str_detect(outcome, "agg|turnout"))

## Combine and do some cleanup / renaming

results_rdd <- list(res_df_rdd_landtag, 
                    res_df_rdd_bundestag, 
                    res_df_rdd_muni)%>% 
  reduce(bind_rows) %>%
  filter(!str_detect(outcome, 'turnout')) %>% 
  mutate(analysis = 'RDD') %>% 
  mutate(exclude_state = ifelse(exclude_state == "State excluded",
                                'B-W excluded', 'Full sample')) %>% 
  mutate(outcome= recode(outcome, 
                         `agg_left` = 'Left-wing\nparties',
                         `agg_center` = 'Centrist\nparties',
                         `agg_right` = 'Right-wing\nparties')) %>% 
  mutate(unit = factor(unit, levels = unique(unit)[c(2,1,3)])) %>% 
  mutate(outcome = factor(outcome, levels = unique(outcome)[c(1,3,2)])) %>% 
  filter(str_detect(exclude_state, 'B-W')) %>% 
  filter(str_detect(outcome, 'Left'))

## Table contents

results_rdd <- results_rdd %>% 
  mutate_at(vars(estimate, se, matches('conf'),
                 pval, bw),
            list(~round(., 5)))

# Table 3: Main results ----

results_rdd %>% 
  dplyr::select(outcome, unit, estimate, se, pval, bw, n) %>% 
  slice(2,1,3)

